package com.zxm.ex.hall.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zxm.ex.common.exception.BackendException;
import com.zxm.ex.common.utils.ToolUtils;
import com.zxm.ex.common.vo.BaseResultVo;
import com.zxm.ex.hall.api.FilmFeginApi;
import com.zxm.ex.hall.controller.HallFilmsVo;
import com.zxm.ex.hall.controller.HallReqVo;
import com.zxm.ex.hall.controller.HallVo;
import com.zxm.ex.hall.dao.entity.MoocFieldT;
import com.zxm.ex.hall.dao.entity.MoocHallFilmInfoT;
import com.zxm.ex.hall.dao.mapper.MoocFieldTMapper;
import com.zxm.ex.hall.dao.mapper.MoocHallFilmInfoTMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashMap;

@Service
public class HallServiceImpl implements IHallService {
    @Autowired
    private MoocFieldTMapper moocFieldTMapper;
    @Autowired
    private  FilmFeginApi filmFeginApi;

    @Autowired
    private MoocHallFilmInfoTMapper moocHallFilmInfoTMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveHall(HallVo hallVo) throws BackendException {
        MoocFieldT moocFieldT = new MoocFieldT();
        moocFieldT.setCinemaId(ToolUtils.str2Int(hallVo.getCinemaId()));
        moocFieldT.setFilmId(ToolUtils.str2Int(hallVo.getFilmId()));
        moocFieldT.setBeginTime(hallVo.getBeginTime());
        moocFieldT.setEndTime(hallVo.getEndTime());
        moocFieldT.setHallId(ToolUtils.str2Int(hallVo.getHallTypeId()));
        moocFieldT.setHallName(hallVo.getHallName());
        moocFieldT.setPrice(ToolUtils.str2Int(hallVo.getFilmPrice()));
        moocFieldTMapper.insert(moocFieldT);

        // 远程调用获取影片信息 缓存到 mooc_hall_film_info_t
        BaseResultVo filmvo = filmFeginApi.getFilmById(hallVo.getFilmId());
        if(null==filmvo.getData()){
            throw  new BackendException(404,"获取影片失败。。");
        }
        LinkedHashMap<String,String> data = (LinkedHashMap<String, String>) filmvo.getData();
        MoocHallFilmInfoT mt = new MoocHallFilmInfoT();
        mt.setFilmId(ToolUtils.str2Int(data.get("filmId")));
        mt.setFilmName(data.get("filmName"));
        mt.setFilmLength(data.get("filmLength"));
        mt.setFilmCats(data.get("filmCats"));
        mt.setActors(data.get("actors"));
        mt.setImgAddress(data.get("imgAddress"));
        moocHallFilmInfoTMapper.insert(mt);
    }

    @Override
    public IPage<HallFilmsVo> getFilmsByCinemaId(HallReqVo hallReqVo) throws BackendException {
        if(0==hallReqVo.getCinemaId()){
            throw  new BackendException(400,"请输入正确的影院编号。。。");
        }
        Page<HallFilmsVo> hallFilmsVoPage = new Page<>(hallReqVo.getNowPage(),hallReqVo.getPageSize());
      return   moocFieldTMapper.getFilmsByCinemaId(hallFilmsVoPage,hallReqVo.getCinemaId());
    }
}
